using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SmartAgricultureService.Core;
using SmartAgricultureService.Models.Tables;
using SmartAgricultureService.Tables;

namespace SmartAgricultureService.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CropsController(DatabaseContext database, IHttpContextAccessor httpContextAccessor) : ControllerBase(httpContextAccessor)
    {
        private const string DEFAULT_CROP_ID = "c7a8f9b1e0d54c769ab3cdef01234567";
        [HttpPost("create")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Create([FromBody] CropInfo cropInfo)
        {
            try
            {
                var hasCrop = await database.Crop.AsNoTracking().AnyAsync(x => x.Name == cropInfo.Name && !x.Delete);
                if (hasCrop)
                    return Reject($"已存在农作物名：{cropInfo.Name}");
                else
                {
                    var cropEntry = new CropEntry
                    {
                        Name = cropInfo.Name,
                        Active = cropInfo.Active,
                        Humidity = cropInfo.Humidity,
                        Id = Guid.NewGuid().ToString("N"),
                        Illumination = cropInfo.Illumination,
                        Temperature = cropInfo.Temperature
                    };
                    await database.Crop.AddAsync(cropEntry);
                    await database.SaveChangesAsync();
                    return Success($"新增农作物成功【{cropEntry.Id}】");
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpPost("update")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Update([FromBody] CropInfo cropInfo)
        {
            try
            {
                var cropEntry = await database.Crop.FirstOrDefaultAsync(x => x.Id == cropInfo.Id && !x.Delete);
                if (cropEntry == null)
                    return Reject($"不存在农作物：{cropInfo.Id}");
                else
                {
                    if (cropEntry.Id != DEFAULT_CROP_ID)
                        cropEntry.Active = cropInfo.Active;
                    cropEntry.Name = cropInfo.Name;
                    cropEntry.Humidity = cropInfo.Humidity;
                    cropEntry.Illumination = cropInfo.Illumination;
                    cropEntry.Temperature = cropInfo.Temperature;
                    await database.SaveChangesAsync();
                    return Success($"更新农作物成功【{cropEntry.Id}】");
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpDelete("del")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Delete(string cropId)
        {
            try
            {
                var cropEntry = await database.Crop.AsTracking().FirstOrDefaultAsync(x => x.Id == cropId && !x.Delete);
                if (cropEntry != null)
                {
                    if (cropEntry.Id != DEFAULT_CROP_ID)
                    {
                        cropEntry.Active = false;
                        cropEntry.Delete = true;
                        await database.SaveChangesAsync();
                    }
                }
                return Success("删除区域成功");
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpGet("getPaging")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> GetPaging(int pageIndex, string keywords, int pageSize = 15)
        {
            try
            {
                if (pageIndex == 0) pageIndex = 1;
                var cropInfos = await database.Crop.AsNoTracking().Where(x => !x.Delete && (string.IsNullOrEmpty(keywords) || x.Name.Contains(keywords))).Paging(pageIndex, pageSize, out var totalPage).ProjectToType<CropInfo>(CropInfo.GetAdapterConfig()).ToListAsync();
                return Paging(pageIndex, totalPage, cropInfos, pageSize);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [Authorize]
        [HttpGet("getAll")]
        public async Task<IActionResult> GetAll()
        {
            try
            {
                var cropInfos = await database.Crop.AsNoTracking().Where(x => !x.Delete && x.Active).ProjectToType<CropInfo>(CropInfo.GetAdapterConfig()).ToListAsync();
                return Success(cropInfos);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
    }
}